package sms

import (
	"context"
	"fmt"
	"io/ioutil"
	"jwgin/service"
	"jwgin/utils"
	ding "jwgin/utils/dingding"
	"jwgin/utils/salt"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type Mb345 struct {
}

func NewMb345() *Mb345 {
	return &Mb345{}
}

func (m *Mb345) SendSms(ip, mobile string) error {

	//手机号校验
	//手机号
	if !utils.CheckMobile(mobile) {
		return fmt.Errorf("手机号格式错误")
	}

	date := time.Now().Hour()
	//验证码
	smskey := fmt.Sprintf("sms:%v", mobile)
	//一天的验证码次数

	rult, err := service.R.Get(context.TODO(), smskey).Result()

	if err != nil && err.Error() != "redis: nil" {
		return err
	}
	if len(rult) > 0 {
		return fmt.Errorf("请求太快了")
	}
	//IP验证码
	IPkey := fmt.Sprintf("sms:%v:%v:%v", date, ip, mobile)
	ipRult, err := service.R.Get(context.TODO(), IPkey).Result()
	if err != nil && err.Error() != "redis: nil" {
		return err
	}
	ipNum, _ := strconv.Atoi(ipRult)
	if ipNum > 20 {
		return fmt.Errorf("当前时间段的IP操作过于火爆,请稍后再来")
	}

	Code := salt.SaltInt(6)
	if _, err = m.send(Code, mobile); err != nil {
		return err
	}

	if ipNum < 1 {
		service.R.Set(context.TODO(), IPkey, 1, time.Hour*1)
	} else {
		service.R.Incr(context.TODO(), IPkey)
	}
	//6位 6分钟的验证码
	service.R.Set(context.TODO(), smskey, Code, time.Minute*6)
	return nil
}

func (Mb345) CheckSms(mobile, code string) bool {
	smskey := fmt.Sprintf("sms:%v", mobile)
	rult, err := service.R.Get(context.TODO(), smskey).Result()
	if err != nil {
		return false
	}
	if rult == code {
		service.R.Del(context.TODO(), smskey)
		return true
	}
	return false

}

func (Mb345) send(code int, mobile string) (ret int64, errs error) {
	sms := service.Conf.Sms
	url := "https://yzm.mb345.com/ws/BatchSend2.aspx"
	utfStr := fmt.Sprintf("验证码为：%v，本次验证码6分钟内有效请勿多次获取【滚滚体育】", code)
	var Content string
	if gb2312Str, err := utils.UTF82GB2312([]byte(utfStr)); err != nil {
		return -2, err
	} else {
		Content = string(gb2312Str)
	}
	payload := strings.NewReader(fmt.Sprintf("CorpID=%s&Pwd=%s&Mobile=%s&Content=%s&Cell=&SendTime=", sms.CorpID, sms.Pwd, mobile, Content))
	req, _ := http.NewRequest("POST", url, payload)
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded; charset=gb2312")
	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)
	var err error
	ret, err = strconv.ParseInt(string(body), 10, 64)
	if err != nil {
		ding.DingErr(err.Error())
	}
	return ret, err
}
